<template>
    <div class="page">
        <h2 class="title">通用合同审批</h2>

        <div class="search">
            <div class="row">
                <label>合同标题：</label>
                <input v-model="input.contractTitle" placeholder="请输入合同标题" />
                <label>对方单位：</label>
                <input v-model="input.counterpartyUnit" placeholder="请输入对方单位" />
                <label>对方负责人：</label>
                <input v-model="input.counterpartyContact" placeholder="请输入对方负责人" />
            </div>
            <div class="row">
                <label>经办人：</label>
                <input v-model="input.handler" placeholder="请输入经办人" />
                <label>签订时间：</label>
                <input type="date" v-model="input.signingStart" />
                <span> - </span>
                <input type="date" v-model="input.signingEnd" />
                <label>状态：</label>
                <select v-model="input.status">
                    <option value="">全部</option>
                    <option value="0">待审批</option>
                    <option value="2">已通过</option>
                    <option value="3">已拒绝</option>
                </select>
                <button class="btn primary" @click="search">查询</button>
                <button class="btn" @click="reset">重置</button>
            </div>
        </div>

        <div class="tabs">
            <button :class="['tab', { active: currentTab === 'all' }]" @click="currentTab = 'all'">全部</button>
            <button :class="['tab', { active: currentTab === 'pending' }]" @click="currentTab = 'pending'">待审批</button>
            <button :class="['tab', { active: currentTab === 'approved' }]"
                @click="currentTab = 'approved'">已审批</button>
        </div>

        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>合同编号</th>
                        <th>合同标题</th>
                        <th>对方单位</th>
                        <th>对方负责人</th>
                        <th>合同类别</th>
                        <th>签订日期</th>
                        <th>经办人</th>
                        <th>创建时间</th>
                        <th>状态</th>
                        <th>审批人</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="loading">
                        <td :colspan="11" style="text-align:center">加载中...</td>
                    </tr>
                    <tr v-else-if="rows.length === 0">
                        <td :colspan="11" style="text-align:center">暂无数据</td>
                    </tr>
                    <tr v-for="r in displayedRows" :key="r.id">
                        <td>{{ r.contractNumber }}</td>
                        <td>{{ r.contractTitle }}</td>
                        <td>{{ r.counterpartyUnit }}</td>
                        <td>{{ r.counterpartyContact }}</td>
                        <td>{{ r.contractType }}</td>
                        <td>{{ r.signingDate }}</td>
                        <td>{{ r.handler }}</td>
                        <td>{{ r.createdAt }}</td>
                        <td>{{ r.status }}</td>
                        <td>{{ r.approver || '-' }}</td>
                        <td>
                            <a href="javascript:void(0)" @click="view(r)">查看</a>
                            &nbsp;|&nbsp;
                            <a href="javascript:void(0)" @click="approve(r)">通过</a>
                            &nbsp;|&nbsp;
                            <a href="javascript:void(0)" @click="reject(r)">拒绝</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="pagination" v-if="total > 0">
            <span class="sum">共{{ totalPage }}页/{{ total }}条数据</span>
            <button class="nav" :disabled="page === 1" @click="goto(page - 1)">‹</button>
            <button v-for="p in pagesToShow" :key="p" class="num" :class="{ active: p === page }" @click="goto(p)">{{ p
            }}</button>
            <button class="nav" :disabled="page >= totalPage" @click="goto(page + 1)">›</button>
            <span class="jump">跳至</span>
            <input class="jump-input" type="number" min="1" :max="Math.max(totalPage, 1)" v-model.number="jumpPage"
                @keyup.enter="jump()" />
            <span class="jump">页</span>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { read, write } from '@/assets/Axios/axiosHttple'

const router = useRouter()
const counts = useCounterStore()

const input = reactive({ contractTitle: '', counterpartyUnit: '', counterpartyContact: '', handler: '', signingStart: '', signingEnd: '', status: '' })
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalPage = ref(0)
const rows = ref<any[]>([])
const loading = ref(false)
const currentTab = ref<'all' | 'pending' | 'approved'>('all')
const jumpPage = ref<number | null>(1)

const pagesToShow = computed(() => {
    const maxPage = Math.max(totalPage.value, 1)
    const cur = Math.min(Math.max(page.value, 1), maxPage)
    const pages: number[] = []
    const start = Math.max(1, cur - 2)
    const end = Math.min(maxPage, cur + 2)
    for (let i = start; i <= end; i++) pages.push(i)
    return pages
})

const displayedRows = computed(() => {
    if (currentTab.value === 'all') return rows.value
    if (currentTab.value === 'pending') return rows.value.filter(r => String(r.status) === '0' || String(r.status) === '待审批')
    return rows.value.filter(r => String(r.status) === '2' || String(r.status) === '已通过' || String(r.status) === '已拒绝')
})

async function fetchList() {
    loading.value = true
    try {
        const params = new URLSearchParams()
        params.append('PageIndex', String(page.value))
        params.append('PageSize', String(pageSize.value))
        if (input.contractTitle) params.append('ContractTitle', input.contractTitle)
        if (input.counterpartyUnit) params.append('CounterpartyUnit', input.counterpartyUnit)
        if (input.counterpartyContact) params.append('CounterpartyContact', input.counterpartyContact)
        if (input.handler) params.append('Handler', input.handler)
        if (input.signingStart) params.append('SigningDate', input.signingStart)
        if (input.status) params.append('ApprovalStatus', input.status)
        params.append('t', String(Date.now()))

        const url = `contractmanagementread/api/ContractManagementControllers/GetGeneralContracts/General`
        const res = await read.get(url, { params })
        const json: any = res?.data ?? {}
        const container = json?.data || {}
        total.value = Number(container?.TotalCount || 0)
        totalPage.value = Number(container?.TotalPage || 0)
        rows.value = Array.isArray(container?.data) ? container.data : []
    } catch (e) {
        console.error(e)
        rows.value = []
        total.value = 0
        totalPage.value = 0
    } finally { loading.value = false }
}

function search() { page.value = 1; fetchList() }
function reset() { Object.assign(input, { contractTitle: '', counterpartyUnit: '', counterpartyContact: '', handler: '', signingStart: '', signingEnd: '', status: '' }); fetchList() }
function goto(p: number) { if (p < 1 || p > totalPage.value) return; page.value = p; fetchList() }

function jump() { if (!jumpPage.value) return; const p = Math.max(1, Math.min(Number(jumpPage.value), Math.max(totalPage.value, 1))); goto(p) }

function view(r: any) { router.push(`/UpdateGeneralContracts?id=${encodeURIComponent(r.id)}`) }
async function approve(r: any) {
    if (!confirm('确认通过？')) return
    try {
        const payload = { id: r.id, approve: true, approvedBy: counts.Logins.Nickname || counts.Logins.Account || '' }
        const candidates = [
            'contractmanagementwrite/api/ContractManagement/ApproveGeneral/general/approve',
            'contractmanagementwrite/api/ContractManagement/Approve/approve'
        ]
        for (const u of candidates) {
            try {
                const res = await write.post(u, payload)
                const d = res?.data ?? {}
                if (res.status === 200 && (Number(d?.code) === 200 || d?.ok === true || d?.data === true)) { fetchList(); return }
            } catch { }
        }
        alert('审批失败，请重试')
    } catch (e) {
        console.error(e)
        alert('审批失败，请重试')
    }
}
async function reject(r: any) {
    if (!confirm('确认拒绝？')) return
    try {
        const payload = { id: r.id, approve: false, approvedBy: counts.Logins.Nickname || counts.Logins.Account || '' }
        const candidates = [
            'contractmanagementwrite/api/ContractManagement/RejectGeneral/general/reject',
            'contractmanagementwrite/api/ContractManagement/Reject/reject'
        ]
        for (const u of candidates) {
            try {
                const res = await write.post(u, payload)
                const d = res?.data ?? {}
                if (res.status === 200 && (Number(d?.code) === 200 || d?.ok === true || d?.data === true)) { fetchList(); return }
            } catch { }
        }
        alert('拒绝失败，请重试')
    } catch (e) { console.error(e); alert('拒绝失败，请重试') }
}

onMounted(() => { fetchList() })
</script>

<style scoped>
.page {
    padding: 16px
}

.title {
    font-size: 18px;
    margin-bottom: 12px
}

.search {
    background: #f7f7f7;
    padding: 12px;
    border-radius: 6px;
    margin-bottom: 12px
}

.row {
    display: flex;
    gap: 8px;
    align-items: center
}

.table {
    width: 100%;
    border-collapse: collapse
}

.table th,
.table td {
    border: 1px solid #eee;
    padding: 8px
}

.pagination {
    margin-top: 12px;
    display: flex;
    gap: 12px;
    align-items: center
}
</style>
